package com.dennytech.tac.ui.activity;

import java.util.Date;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

import com.dennytech.tac.base.CFActivity;
import com.dennytech.tac.model.Record;
import com.dennytech.tac.statistics.Stat;
import com.dennytech.tac.utils.Daemon;
import com.dennytech.tac.utils.db.TimelineDBHelper;
import com.dennytech.tac.widget.LocalImageView;
import com.dennytech.tac.R;

public class AddRecordActivity extends CFActivity {

	private String image;
	private LocalImageView liv;
	private EditText intro;

	private Record record;

	Handler handler = new Handler(Daemon.looper()) {
		@Override
		public void handleMessage(Message msg) {
			TimelineDBHelper dbHelper = TimelineDBHelper.instance();

			if (msg.what == 0) {
				dbHelper.insert((Record) msg.obj);
			} else if (msg.what == 1) {
				dbHelper.update((Record) msg.obj);
				Toast.makeText(
						AddRecordActivity.this,
						getResources().getString(
								R.string.message_update_success),
						Toast.LENGTH_SHORT).show();
			}

		}
	};

	@Override
	protected void onCreate(Bundle b) {
		super.onCreate(b);

		record = getIntent().getParcelableExtra("record");

		if (record != null) {
			liv.setImage(record.getImage());
			intro.setText(record.getIntro());
		} else {
			Uri uri = getIntent().getData();
			image = uri.getQueryParameter("image");
			liv.setImage(image);
		}

	}

	@Override
	protected void initView() {
		setContentView(R.layout.add_record);
		liv = (LocalImageView) findViewById(R.id.photo);
		intro = (EditText) findViewById(R.id.intro);
		
		liv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Stat.event("addrecord", "addrecord_img_click", null, 0);
			}
		});
	}

	@Override
	public void finish() {
		String introStr = intro.getText().toString().trim();

		if (record != null) {
			if (introStr.equals(record.getIntro())) {
				super.finish();
				return;
			}
			record.setIntro(introStr);
			handler.sendMessage(handler.obtainMessage(1, record));

		} else {
			Record r = new Record();
			r.setImage(image);
			r.setIntro(introStr);
			r.setDateStr(new Date());
			handler.sendMessage(handler.obtainMessage(0, r));
		}
		
		Stat.event("addrecord", "addrecord_content", String.valueOf(introStr.length()), 0);

		setResult(RESULT_OK);
		super.finish();
	}

}
